<template>
  <div class="app">
    <!-- 登录页面不需要侧边栏和头部 -->
    <router-view v-if="!isAuthenticated"></router-view>
    
    <!-- 已登录用户的管理系统布局 -->
    <div v-else class="management-layout">
      <!-- 侧边栏 -->
      <el-container>
        <el-aside :width="isCollapse ? '64px' : '240px'" class="aside">
          <div class="logo-container" :class="{ 'collapsed': isCollapse }">
            <el-avatar size="40" icon="el-icon-office-building" :style="{ backgroundColor: '#409eff' }"></el-avatar>
            <span v-if="!isCollapse" class="logo-text">管理系统</span>
          </div>
          
          <el-menu
            :default-active="activeMenu"
            class="el-menu-vertical"
            :collapse="isCollapse"
            text-color="#fff"
            active-text-color="#409EFF"
            background-color="#001529"
            router
          >
            <el-sub-menu index="1">
              <template #title>
                <el-icon><HomeFilled /></el-icon>
                <span>首页</span>
              </template>
              <el-menu-item index="/">
                <el-icon><Document /></el-icon>
                <span>数据总览</span>
              </el-menu-item>
            </el-sub-menu>
            <el-sub-menu index="2">
              <template #title>
                <el-icon><User /></el-icon>
                <span>用户管理</span>
              </template>
              <el-menu-item index="/users">
                <el-icon><User /></el-icon>
                <span>用户列表</span>
              </el-menu-item>
            </el-sub-menu>
            <el-sub-menu index="3">
              <template #title>
                <el-icon><Goods /></el-icon>
                <span>产品管理</span>
              </template>
              <el-menu-item index="/products">
                <el-icon><Menu /></el-icon>
                <span>产品列表</span>
              </el-menu-item>
            </el-sub-menu>
            <el-sub-menu index="4">
              <template #title>
                <el-icon><Setting /></el-icon>
                <span>系统设置</span>
              </template>
              <el-menu-item index="/settings">
                <el-icon><Setting /></el-icon>
                <span>系统配置</span>
              </el-menu-item>
            </el-sub-menu>
          </el-menu>
        </el-aside>
        
        <el-container class="main-container">
          <!-- 顶部导航栏 -->
          <el-header class="header">
            <div class="header-left">
              <el-button
                circle
                plain
                icon="el-icon-s-fold"
                :size="isCollapse ? 'default' : 'large'"
                @click="toggleCollapse"
              ></el-button>
            </div>
            
            <div class="header-right">
              <el-dropdown>
                <span class="user-dropdown">
                  <el-avatar size="small" :src="currentUser.avatar || ''">
                    {{ getAvatarText(currentUser.name || currentUser.username || '管') }}
                  </el-avatar>
                  <span class="user-name">{{ currentUser.name || currentUser.username || '管理员' }}</span>
                  <el-icon class="el-icon--right"><ArrowDown /></el-icon>
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="goToSettings">
                      <el-icon><Setting /></el-icon>
                      <span>设置</span>
                    </el-dropdown-item>
                    <el-dropdown-item divided @click="handleLogout">
                      <el-icon><SwitchButton /></el-icon>
                      <span>退出登录</span>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </el-header>
          
          <!-- 主内容区域 -->
          <el-main class="content-wrapper">
            <router-view v-slot="{ Component }">
              <transition name="fade" mode="out-in">
                <component :is="Component" />
              </transition>
            </router-view>
          </el-main>
        </el-container>
      </el-container>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { isLoggedIn, deleteCookie } from './utils/cookieUtils.js'
import {
  HomeFilled,
  User,
  Goods,
  Setting,
  Document,
  Menu,
  ArrowDown,
  SwitchButton
} from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()
const currentUser = ref({})
const isCollapse = ref(false)

// 计算当前激活的菜单项
const activeMenu = computed(() => {
  return route.path
})

// 检查用户是否已认证
const isAuthenticated = computed(() => {
  return isLoggedIn()
})

// 加载当前用户信息
const loadCurrentUser = () => {
  if (isLoggedIn()) {
    // 从localStorage获取用户信息
    const userStr = localStorage.getItem('currentUser')
    if (userStr) {
      currentUser.value = JSON.parse(userStr)
    } else {
      // 设置默认管理员信息
      const defaultUser = {
        name: '管理员',
        username: 'admin'
      }
      currentUser.value = defaultUser
      localStorage.setItem('currentUser', JSON.stringify(defaultUser))
    }
  }
}

// 获取头像文字
const getAvatarText = (name) => {
  if (!name) return '用'
  return name.charAt(0)
}

// 切换侧边栏折叠状态
const toggleCollapse = () => {
  isCollapse.value = !isCollapse.value
}

// 跳转到设置页面
const goToSettings = () => {
  router.push('/settings')
}

// 处理退出登录
const handleLogout = () => {
  // 清除用户相关信息
  deleteCookie('sso_token') // 清除Cookie中的token
  localStorage.removeItem('currentUser')
  localStorage.removeItem('rememberedUsername')
  localStorage.removeItem('rememberedPassword')
  
  ElMessage.success('退出登录成功')
  
  // 使用replace而不是push，并强制重新加载页面
  router.replace('/login').then(() => {
    // 强制重新加载页面，确保App.vue完全重新渲染
    window.location.reload()
  })
}

// 监听路由变化，确保用户已登录
watch(() => route.path, (newPath) => {
  if (newPath !== '/login' && !isAuthenticated.value) {
    router.push('/login')
  }
})

// 组件挂载时加载用户信息
onMounted(() => {
  loadCurrentUser()
})
</script>

<style>
/* 全局样式重置 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
  line-height: 1.6;
  color: #333;
  background-color: #f5f7fa;
}

#app {
  height: 100vh;
}

/* 淡入淡出过渡效果 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

/* 应用容器样式 */
.app {
  min-height: 100vh;
}

/* 管理系统布局 */
.management-layout {
  height: 100vh;
}

/* 侧边栏样式 */
.aside {
  background-color: #001529;
  overflow: hidden;
  transition: width 0.3s;
}

.logo-container {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 16px;
  color: white;
  transition: justify-content 0.3s;
}

.logo-container.collapsed {
  justify-content: center;
}

.logo-text {
  margin-left: 10px;
  font-size: 18px;
  font-weight: 600;
}

.el-menu-vertical {
  border-right: none;
  height: calc(100vh - 60px);
  overflow-y: auto;
}

/* 主容器样式 */
.main-container {
  height: 100vh;
}

/* 头部导航样式 */
.header {
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  height: 60px;
}

.header-left {
  display: flex;
  align-items: center;
}

.header-right {
  display: flex;
  align-items: center;
}

.user-dropdown {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 5px 10px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.user-dropdown:hover {
  background-color: #f5f7fa;
}

.user-name {
  margin: 0 10px;
  font-size: 14px;
}

/* 主内容区域样式 */
.content-wrapper {
  padding: 20px;
  overflow-y: auto;
  background-color: #f5f7fa;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .aside {
    width: 64px !important;
  }
  
  .logo-text {
    display: none;
  }
  
  .el-menu-vertical {
    collapse-transition: 0s;
  }
}
</style>